//
//  CollectionViewViewController.swift
//  MacStudy
//
//  Created by 30san on 2020/10/9.
//  Copyright © 2020 Dawninest. All rights reserved.
//

import Cocoa

class CollectionViewViewController: NSViewController {

    @IBOutlet weak var collectionView: NSCollectionView!
    private let itemID = "CollectionViewItemID"
    private var dataSources: [NSImage] = Array()
    private let pasteboardTypeCustom = NSPasteboard.PasteboardType(rawValue: "pasteboardTypeCustom")
    
    override func viewDidLoad() {
        super.viewDidLoad()
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.register(CollectionViewItem.self, forItemWithIdentifier: NSUserInterfaceItemIdentifier.init(itemID))
        let flowLayout = NSCollectionViewFlowLayout()
        flowLayout.itemSize = NSMakeSize(100, 100)
        flowLayout.minimumLineSpacing = 20
        flowLayout.minimumInteritemSpacing = 20
        self.collectionView.collectionViewLayout = flowLayout
        loadDatas()
        
        // 注册拖拽类型
        collectionView.registerForDraggedTypes([pasteboardTypeCustom])
//        collectionView.setDraggingSourceOperationMask(NSDragOperation.every, forLocal: true)
    }
    
    func loadDatas() {
        let path = NSSearchPathForDirectoriesInDomains(.applicationDirectory, .systemDomainMask, true).first!
        let url = URL(fileURLWithPath: path)
        let dirEnumerator = FileManager.default.enumerator(at: url, includingPropertiesForKeys: [URLResourceKey.isApplicationKey, URLResourceKey.effectiveIconKey], options: FileManager.DirectoryEnumerationOptions.skipsSubdirectoryDescendants, errorHandler: nil)
        while ((dirEnumerator?.nextObject()) != nil) {
            var iconImage: AnyObject? = nil
            guard let item = dirEnumerator?.nextObject() else {
                return
            }
            do {
                try (item as! NSURL).getResourceValue(&iconImage, forKey: URLResourceKey.effectiveIconKey)
                dataSources.append(iconImage as! NSImage)
            } catch {
                
            }
        }
    }
}


extension CollectionViewViewController: NSCollectionViewDataSource {
    func collectionView(_ collectionView: NSCollectionView, numberOfItemsInSection section: Int) -> Int {
        return dataSources.count
    }
    
    func collectionView(_ collectionView: NSCollectionView, itemForRepresentedObjectAt indexPath: IndexPath) -> NSCollectionViewItem {
        let cell = collectionView.makeItem(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: itemID), for: indexPath) as! CollectionViewItem
        cell.contentImageView.image = dataSources[indexPath.item]
        return cell
    }
}


extension CollectionViewViewController: NSCollectionViewDelegate {
    // drag
//    func collectionView(_ collectionView: NSCollectionView, draggingSession session: NSDraggingSession, willBeginAt screenPoint: NSPoint, forItemsAt indexPaths: Set<IndexPath>) {
//        print("draggingSession indexPaths = \(indexPaths)")
//    }
//    
//    func collectionView(_ collectionView: NSCollectionView, pasteboardWriterForItemAt index: Int) -> NSPasteboardWriting? {
//        let item = NSPasteboardItem()
//        let data = dataSources[index].tiffRepresentation
//        let result = item.setData(data!, forType: pasteboardTypeCustom)
//        return item
//    }
//
//    func collectionView(_ collectionView: NSCollectionView, acceptDrop draggingInfo: NSDraggingInfo, indexPath: IndexPath, dropOperation: NSCollectionView.DropOperation) -> Bool {
//         print("acceptDrop  indexPath = \(indexPath)")
//        return true
//    }
//
//    func collectionView(_ collectionView: NSCollectionView, validateDrop draggingInfo: NSDraggingInfo, proposedIndex proposedDropIndex: UnsafeMutablePointer<Int>, dropOperation proposedDropOperation: UnsafeMutablePointer<NSCollectionView.DropOperation>) -> NSDragOperation {
//        print("draggingInfo")
//        return .move
//    }
    
    // Select   需要在storyboard中 selection  勾选 Selectable
    func collectionView(_ collectionView: NSCollectionView, didSelectItemsAt indexPaths: Set<IndexPath>) {
        print("indexPaths = \(indexPaths)")
    }
}
